package Offer.offer2017;

/**
 * 数字在排序数组中出现的次数
 * Created by 雷文康 on 2018/1/4.
 */
public class Test38 {

    public static void main(String[] args) {
        int[] array={3,3,3,3,3,4,4,5};
        System.out.println(getNumberOfK(array, 3));
    }

    public static int getNumberOfK(int[] array, int K){
        if (array == null || array.length == 0){
            return -1;
        }
        int first = getFirstK(array, 0, array.length - 1, K);
        int last = getLastK(array, 0, array.length - 1, K);
        if (first > -1 && last > -1){
            return last - first + 1;
        }
        return -1;
    }

    private static int getFirstK(int[] array, int start, int end, int K){
        while (start <= end) {
            int mid = (start + end) / 2;
            if (array[mid] == K) {
                if (mid == 0 || array[mid - 1] != K){
                    return mid;
                } else {
                    end = mid - 1;
                }
            } else if (array[mid] < K) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }

    private static int getLastK(int[] array, int start, int end, int K){
        while (start <= end) {
            int mid = (start + end) / 2;
            if (array[mid] == K) {
                if (mid == end || array[mid + 1] != K){
                    return mid;
                } else {
                    start = mid + 1;
                }
            } else if (array[mid] < K) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }
}

